'use strict';
const fs = require('fs')
const path = require('path')
const FormData = require('form-data');
let uniID=require('uni-id')
const uniCaptcha=require('uni-captcha')
const createConfig=require('uni-config-center')
const uniIdConfig = createConfig({
	pluginId:'uni-id'
}).config()
const db = uniCloud.database();
const dbCmd=db.command
const {appid,appsecret}=uniIdConfig['mp-weixin'].oauth.weixin
exports.main = async (event, context) => {
	let uniIDIns=uniID.createInstance({
		context
	})
	console.log('event : ', event)
	const {action,uniIdToken}=event
	const deviceInfo=event.deviceInfo||{};
	let {params}= event || {}
	console.log(params)
	var miniUrl=`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appsecret}&js_code=${params}&grant_type=authorization_code`
	// 身份校验（检查token）
	let noCheckToken=['login','register','loginByWeixin',
	'checkToken','logout','createCaptcha','emailLogin','setCode']
	// 前端用户做token检验
	if(!noCheckToken.includes(action)){
		if(!uniIdToken){
			return {
				code:'403',
				msg:'缺少token'
			}
		}
		let payload=await uniIDIns.checkToken(uniIdToken)
		if(payload.code && payload.code!=0){
			return payload
		}
		// 将获取到的uid赋值给params
		params.uid=payload.uid
	}
	// 注册成功后，添加用户的设备信息
	async function registerSuccess(uid){
		db.collection('uni-id-device').add({
			...deviceInfo,
			user_id:uid
		})
	}
	// 添加设备登录日志
	const loginLog=async (res={})=>{
		const uniIdlogCollection=db.collection('uni-id-log')
		let logData={
			deviceId:params.deviceId || context.DEVICEID,
			ip: params.ip || context.CLIENTIP,
			create_date:Date.now(),
			type:res.type,
			ua:context.CLIENTUA
		}	
		if(res.code==0){
			logData.user_id=res.uid
			logData.state=1
			if(res.type=='register'){ 
				await registerSuccess(res.uid)
			}else{
				if(Object.keys(deviceInfo).length){
					// 更新设备信息
					await db.collection('uni-id-device').where({
						user_id:res.uid
					}).update(deviceInfo)
				}
			}
		}else{
			logData.state=0
		}
		return await uniIdlogCollection.add(logData)
	}
	let res={}
	
	switch (action){
		case "login":
			//查找登陆日志是否在两小时内，有两次输错的记录 
			const getNeedCaptcha=async ()=>{
				const now =Date.now(),
				recordDate=120*60*1000,
				recordSize=2;
				const uniIdlogCoolection=db.collection('uni-id-log')
				let recentRecord=await uniIdlogCoolection.where({
					deviceId:params.deviceId || context.DEVICEID,
					create_date:dbCmd.gt(now-recordDate),
					type:'login'
				}).orderBy('create_date','desc')
				.limit(recordSize).get()
				console.log(recentRecord)
				return recentRecord.data.filter(item=>item.state==0).length==recordSize;
			}
			let passed=false
			// 查询是否有过登录次数失败,看是否需要验证码
			let needCaptcha=await getNeedCaptcha();
			console.log(needCaptcha)
			// 需要验证码
			if(needCaptcha){
				// 校验验证码
				res = await uniCaptcha.verify({
					...params,
					scene:"login",
				})
				if(res.code==0) passed=true
			}
			if(!needCaptcha || passed){
				res=await uniIDIns.login({
					...params,
					queryField: ['username', 'email', 'mobile']
				})
				console.log(res)
				res.type='login'
				// 添加登陆日志
				await loginLog(res)
				// 这次返回的肯定是false
				needCaptcha=await getNeedCaptcha();
			}
			res.needCaptcha=needCaptcha
		break;
		case "register":
			var {username,password,nickname}=params
			if(/^1\d{10}$/.test(username)){
				return {
					code:401,
					message:'用户名不能是手机号'
				}
			}
			if(/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(username)){
				return {
					code:401,
					message:'用户名不能是邮箱'
				}
			}
			res=await uniIDIns.register({
				username,
				password,
				nickname
			})
			console.log(res)
			if(res.code==0){
				// 注册成功后，用户设备信息的存储
				await registerSuccess(res.uid)
			}
		break;
		case 'logout':
			res=await uniIDIns.logout(uniIdToken)
			console.log(res)
		break;
		case 'createCaptcha':
		  res = await uniCaptcha.create(params);
		  console.log(res)
		break;
		case 'refreshCaptcha':
			res=await uniCaptcha.refresh(params)
			console.log(res)
		break;
		case 'amendPws':
			var {oldPassword,newPassword}=params
			res=await uniIDIns.updatePwd({
				uid:params.uid,
				oldPassword,
				newPassword
			})
			console.log(res)
		break;
		case 'loginByWeixin':
			// console.log(miniUrl)
			// res= await uniCloud.httpclient.request(miniUrl,{
			// 	method:'GET',
			// 	contentType: 'json', // 指定以application/json发送data内的数据
			// 	dataType: 'json' // 指定返回值为json格式，自动进行parse
			// })
			// console.log(res)
			let loginRes=await uniIDIns.loginByWeixin(params);
			console.log('kanshuju ')
			console.log(loginRes)
			if(loginRes.code==0){
				if(context.PLATFORM=='mp-weixin'){
					let resUpdateUser=await uniIDIns.updateUser({
							uid:loginRes.uid,
							openid:loginRes.openid
					})
					console.log(resUpdateUser)
				}
				// delete loginRes.openid
				// delete loginRes.sessionKey
				// delete loginRes.accessToken
				// delete loginRes.refreshToken
				// delete loginRes.userInfo.sessionKey
				// delete loginRes.userInfo.wx_openid
			}
			console.log(loginRes)
			await loginLog(loginRes)
			return loginRes
		break;
		case 'wxBizDataCrypt':
			let resInfo=await uniIDIns.wxBizDataCrypt({
				encryptedData:params.encryptedData,
				iv:params.iv,
				sessionKey:params.sessionKey
			})
			console.log('数据')
			console.log(resInfo)
			let resUpdateUser=await uniIDIns.updateUser({
				uid:params.uid,
				nickName:resInfo.nickName,
				gender:resInfo.gender,
				avatar:resInfo.avatarUrl,
				// wx_openid.mp-weixin:resInfo.openId
			})
			console.log(resUpdateUser)
			return resInfo
		break;
		case 'idCard':
			let data=await db.collection('setconfig').get()
			console.log(data)
			let url=`https://api.weixin.qq.com/cv/ocr/idcard?type=photo&access_token=${data.data[0].accessToken}`
			res= await uniCloud.httpclient.request(url,{
				method:'POST',
				data: {
				    img_url: params.imageurl,
				},
				contentType: 'json', // 指定以application/json发送data内的数据
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
			console.log(res)
			return res
		break;
		case 'imgSecCheck':
			const form = new FormData()
			form.append('media', fs.readFileSync(path.resolve(__dirname, './test.jpg')), { // 为方便演示此处直接使用云函数目录下的test.jpg文件
				filename: 'test.jpg',
				contentType: 'image/jpeg'
			});
		    // form.append('otherParam', 'otherParam content');
			let datas=await db.collection('setconfig').get()
			console.log(datas)
			let urls=`https://api.weixin.qq.com/wxa/img_sec_check?access_token=${datas.data[0].accessToken}`
			res=await uniCloud.httpclient.request(urls,{
				method:'POST',
				content: form.getBuffer(), // 请求内容
				headers: form.getHeaders(), // 请求头
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
			console.log(res)
			return res
		break;
		case 'emailLogin':
			// 检验验证码(验证码只能校验一次，之后会失效，所以在登陆之前不用校验，直接设置即可登录)
			// const result1 = await uniID.verifyCode({
			// 	...params,
			// })
			// console.log(result1)
			// if(result1.code!=0){
			// 	return result1
			// }
			res=await uniIDIns.loginByEmail({
				...params,
			})
			console.log(res)
		break;
		case 'setCode':
			return await uniIDIns.setVerifyCode({
				email:params.email,
				code:params.code,
				type:params.type,
				expiresIn: 300,
			})
		break;
		// 删除文件
		case "deleteFile":
			console.log(params.fileId)
			res= await uniCloud.deleteFile({
				fileList:params.fileId,
				// fileList:[ "https://vkceyugu.cdn.bspapp.com/VKCEYUGU-62ec721a-a0ff-4726-a9f0-0e206b972095/3d8f0ac8-9f52-4784-b050-344295b45766.jpg"]
			})
			console.log(res)
		break;
		default:
			res={
				code:'403',
				msg:"非法访问"
			}
		break;
	}
	
	//返回数据给客户端
	return res
};
